package com.letv.business.flow.album;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import com.letv.android.young.client.R;
import com.letv.business.flow.album.AlbumPlayFlowObservable.PlayErrorCodeNotify;
import com.letv.business.flow.album.AlbumPlayFlowObservable.VideoTitleNotify;
import com.letv.business.flow.play.PlayStatisticsUtils;
import com.letv.core.bean.FloatBallBeanList;
import com.letv.core.bean.PlayRecord;
import com.letv.core.bean.VideoBean;
import com.letv.core.constant.PlayConstant;
import com.letv.core.constant.PlayConstant.PlayErrCode;
import com.letv.core.db.DBManager;
import com.letv.core.db.PreferencesManager;
import com.letv.core.network.volley.Volley;
import com.letv.core.network.volley.VolleyResponse.NetworkResponseState;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.PlayUtils.PLAY_LEVEL;
import com.letv.datastatistics.util.DataConstant;

/**
 * 点播专题流程
 * 
 * @author zhuqiao
 *
 */
public class AlbumPlayTopicFlow extends AlbumPlayFlow {
    protected static final String REQUEST_TOPIC_ALBUM_LIST = "RequestTopicAlbumList";

    // private int mType;
    private long mPid;
    private long mPvid;

    // private TopicDetailInfoListBean mTopicDetailInfoList;

    public AlbumPlayTopicFlow(Context context, int launchMode, Bundle bundle) {
        super(context, launchMode, bundle);
    }

    @Override
    protected void initDataFromIntent(Bundle bundle) {
        mFrom = bundle.getInt(PlayConstant.FROM, PlayConstant.LAUNCH_FROM_CHANNEL);
        mBackToOriginalApp = bundle.getBoolean(PlayConstant.BACK);
    }

    @Override
    protected void initDataWithLaunchMode(Bundle bundle) {
        mZid = Math.max(0, bundle.getLong(PlayConstant.ZID));
        // mType = Math.max(AlbumNew.Type.VRS_MANG, bundle.getInt(PlayConstant.TYPE, AlbumNew.Type.VRS_MANG));
        mPid = Math.max(0, bundle.getLong(PlayConstant.PID));
        mPvid = Math.max(0, bundle.getLong(PlayConstant.PVID));
        mVid = 0;
        mIsDolby = bundle.getBoolean(PlayConstant.IS_DOLBY);
        mSeek = bundle.getLong(PlayConstant.SEEK);
    }

    @Override
    public void start() {
        super.start();
    }

    @Override
    public void startLoadingData() {
        super.startLoadingData();
        if (mLaunchMode == PlayConstant.PLAY_TOPIC_ALBUM) {
            // requestTopicAlbumList();
            mAid = mPid;
            mVid = mPvid;
            sRequestRealUrlConsumetime = System.currentTimeMillis();
//            checkPlayRecord(true);
        } else if (getLaunchMode() == PlayConstant.PLAY_TOPIC_VIDEO) {
            // requestTopicAlbumList();
            mAid = mPid;
            mVid = mPvid;
            sRequestRealUrlConsumetime = System.currentTimeMillis();
//            checkPlayRecord(false);
        } else {
            if (!TextUtils.isEmpty(mAlbumUrl.realUrl)) {// 直接给播放地址的播放
                mVideoListener.initVideoView(false);
                mVideoListener.startPlayLocal(mAlbumUrl.realUrl, (int) mSeek * 1000);
                mLocalPath = mAlbumUrl.realUrl;
                mLocalSeek = mSeek;
            }
        }
    }


//    @Override
    protected void onRequestPlayRecord(PlayRecord result) {
        if (mIsDownloadFile && mDownloadDBBean != null) {
            mObservable.notifyObservers(new VideoTitleNotify(mDownloadDBBean.getEpisodetitle()));
        } else if (result != null && !TextUtils.isEmpty(result.getTitle())) {
            mObservable.notifyObservers(new VideoTitleNotify(result.getTitle()));
        }

        if (result != null && "180003".equals(result.getVideoType())) {
            result = null;
        }

        mPlayRecord = result;

        if (mPlayRecord != null) {
            // dlna
            if (mPlayRecord.getTotalDuration() > 1800) {
                mLoadListener.loadingStart(LetvUtils.getPlayRecordType(mContext, mPlayRecord, mPlayInfo.beginTime),
                        null);
            }
            if (mSeek > 0) {
                mPlayRecord.setPlayedDuration(mSeek / 1000);
            }
            mVid = mPlayRecord.getVideoId();
            mPlayInfo.currTime = mPlayRecord.getPlayedDuration() * 1000;
            mPlayInfo.totalTime = mPlayRecord.getTotalDuration() * 1000;
        }

        requestVideo(false);
        notifyTabRequestData();
    }

    /**
     * 请求合并接口
     */
    @Override
    protected void requestVideo(boolean isNextPlayer) {
        mObservable.notifyObservers(AlbumPlayFlowObservable.ON_START_FETCHING);
        Volley.getQueue().cancelWithTag(REQUEST_VIDEO_PLAY_URL);

        // 播放器初始化
        mHasInited = false;
        mIsFirstPlay = true;

        RequestVideoPlayUrl request = new RequestVideoPlayUrl() {

//            @Override
            protected void onError(NetworkResponseState state) {
                if (state == NetworkResponseState.NETWORK_NOT_AVAILABLE) {
                    if (mIsDownloadFile) {
                        startPlayLocal();
                        return;
                    }

                    mLoadListener.requestError("", "");
                    mObservable.notifyObservers(new PlayErrorCodeNotify("", true));
                    mPlayCallBackState = 2;
                } else if (state == NetworkResponseState.RESULT_ERROR) {
                    mLoadListener.requestError(mContext.getString(R.string.commit_error_info),
                            PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED);
                    mObservable.notifyObservers(new PlayErrorCodeNotify(PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED,
                            true));
                } else if (state == NetworkResponseState.NETWORK_ERROR) {
                    mLoadListener.requestError(mContext.getString(R.string.commit_error_info),
                            PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED);
                    mObservable.notifyObservers(new PlayErrorCodeNotify(PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED,
                            true));
                }
            }

        };
        request.startRequestCache();
    }

    @Override
    protected void startPlayLocal() {
        mIsScanVideo = false;
        mVideoListener.resetPlayFlag();
        mIsShowSkipEnd = true;
        mIsP2pMode = false;

        if (mIsDownloadFile) {
            PlayStatisticsUtils.updatePlayDataStatistics(getContext(),this, DataConstant.StaticticsVersion2Constatnt.PlayerAction.PLAY_ACTION, -1, true);
        }

        if (mDownloadDBBean != null) {
            mPlayLevel = mDownloadDBBean.getIsHd() == 1 ? PLAY_LEVEL.HIGH : PLAY_LEVEL.STANDARD;
            mStreamSupporter.hasSuperHd = false;
            if (mPlayLevel == PLAY_LEVEL.HIGH) {
                mCurrDownloadFileIsHd = true;
                mStreamSupporter.hasHd = true;
                mStreamSupporter.hasStandard = false;
            } else {
                mStreamSupporter.hasHd = false;
                mStreamSupporter.hasStandard = true;
            }
            mStreamSupporter.hasLow = false;
        } else {
            mPlayLevel = PLAY_LEVEL.HIGH;
            mCurrDownloadFileIsHd = true;
            mStreamSupporter.reset();
            mStreamSupporter.hasHd = true;
        }

        addOffAd();
    }


    @Override
    public void setVideoBean(VideoBean video) {
        mCurrentPlayingVideo = video;
        if (video != null) {
            mObservable.notifyObservers(new VideoTitleNotify(video.getNameCn()));
            mPlayInfo.endTime = video.getEtime();
            mPlayInfo.beginTime = video.getBtime();
            // dlna
            if (video.getDuration() > 1800) {
                mLoadListener.loadingStart(LetvUtils.getPlayRecordType(mContext, mPlayRecord, mPlayInfo.beginTime),
                        null);
            }
            if (video != null && video.getDuration() < 180) {
                if (mPlayRecord != null) {
                    mPlayRecord.setPlayedDuration(0);
                }
            }

            if (DBManager.getInstance().getDownloadTrace().isInFinish(video.getId() + "")
                    || DBManager.getInstance().getWorldCupTrace().isInFinish(video.getId() + "")) {
                mIsP2pMode = false;
            } else {
                mIsP2pMode = PreferencesManager.getInstance().getUtp();
            }
        } else {
            mPlayInfo.endTime = 0;
            mPlayInfo.beginTime = 0;
        }
    }

    @Override
    protected void handlerFloatBall() {
        if (mCurrentPlayingVideo != null) {
            mVideoListener.handlerFloatBall(FloatBallBeanList.FLOAT_TOPIC_HALF_NINE, mCurrentPlayingVideo.getCid());
        }
    }

}
